package com.zzsy.carosshopprojects.activitys.home.mainpage.barmanager.membershipcard;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.king.base.util.ToastUtils;
import com.zzsy.carosshopprojects.R;
import com.zzsy.carosshopprojects.base.BaseFragment;
import com.zzsy.carosshopprojects.base.ConfigureFile;
import com.zzsy.carosshopprojects.bean.BaseBean;
import com.zzsy.carosshopprojects.bean.CardZBBean;
import com.zzsy.carosshopprojects.bean.MessageEvent;
import com.zzsy.carosshopprojects.network.RequestUtils;
import com.zzsy.carosshopprojects.network.Utils.MyObserver;
import com.zzsy.carosshopprojects.util.ConverterHelper;
import com.zzsy.carosshopprojects.util.DataUtil;
import com.zzsy.carosshopprojects.util.StringUtils;
import com.zzsy.carosshopprojects.util.ViewBgUtil;
import com.zzsy.carosshopprojects.view.dialog.GoUpPopupDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

/**
 * 添加副卡填写资料界面
 */
public class FillInInformationFragment extends BaseFragment {
    public static FillInInformationFragment newInstance(String mainCardId, String productId, String id) {
        FillInInformationFragment fillInInformationFragment = new FillInInformationFragment();
        Bundle bundle = new Bundle();
        bundle.putString("mainCardId", mainCardId);
        bundle.putString("productId", productId);
        bundle.putString("id", id);
        fillInInformationFragment.setArguments(bundle);
        return fillInInformationFragment;
    }

    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_phone_one)
    EditText etPhoneOne;
    @BindView(R.id.et_phone_two)
    EditText etPhoneTwo;
    @BindView(R.id.et_new_money)
    EditText etNewMouney;
    @BindView(R.id.ly_main)
    LinearLayout ly_main;

    private String fuCardName;
    private String onePhone;
    private String twoPhone;
    private String newMoney;
    private String mainCardId;
    private String id;
    private String productId;
    private String carNumber;


    @Override
    protected int initLayout() {
        return R.layout.fg_fillininformation;
    }

    @Override
    protected void initView(View view) {
        ly_main.setBackground(ViewBgUtil.setBg(15, Color.parseColor(ConfigureFile.ColorWhite)));
        initTitle(view, getResources().getString(R.string.InputMessage), getActivity());
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        tvNext.setOnClickListener(view1 -> {
            fuCardName = etName.getText().toString().trim();
            onePhone = etPhoneOne.getText().toString().trim();
            twoPhone = etPhoneTwo.getText().toString().trim();
            newMoney = etNewMouney.getText().toString().trim();

            if (StringUtils.isEmpty(fuCardName)) {
                ToastUtils.showToast(getContext(), "请填写副卡人姓名!");
                return;
            }

            if (StringUtils.isEmpty(onePhone) || StringUtils.isEmpty(twoPhone)) {
                ToastUtils.showToast(getContext(), "请填写电话号!");
                return;
            }

            if (onePhone.length() != 11 || twoPhone.length() != 11) {
                ToastUtils.showToast(getContext(), "请检查电话号格式!");
                return;
            }
            if (!onePhone.equals(twoPhone)) {
                ToastUtils.showToast(getContext(), "确认手机号不同，请检查!");
                return;
            }

            if (StringUtils.isEmpty(newMoney)) {
                ToastUtils.showToast(getContext(), "请填写分配额度!");
                return;
            }

            if ("0".equals(newMoney)) {
                ToastUtils.showToast(getContext(), "请输入正确的额度!");
                return;
            }
            GoUpPopupDialog.newInstance(0, false, GoUpPopupDialog.REPLACEMENTCARD).show(getFragmentManager(), "dialog");

        });
    }

    @Override
    protected void initData(Context mContext) {
        mainCardId = getArguments().getString("mainCardId");
        id = getArguments().getString("id");
        productId = getArguments().getString("productId");
    }

    @Override
    protected void loadMethod() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        switch (event.message) {
            case MessageEvent.REPLACEMENTCARD:
                getCardNo(event.content);
                break;
        }
    }

    private void getCardNo(String uuid) {
        RequestUtils.CarPreparation(getContext(), DataUtil.getInstance().getStoreId(), uuid, new MyObserver<CardZBBean>(getContext()) {
            @Override
            public void onSuccess(CardZBBean result) {
                if (result != null) {
                    carNumber = result.getCarNumber();
                    if (StringUtils.isEmpty(carNumber)) {
                        ToastUtils.showToast(getContext(), "获取卡号失败!");
                        return;
                    }
                    getTokens(uuid, carNumber);

                } else {
                    ToastUtils.showToast(getContext(), "该门店暂无开卡服务!");
                    goBack(getActivity());
                }
            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                ToastUtils.showToast(getContext(), errorMsg);
            }
        });
    }

    public void getTokens(String uuid, String carNumber) {
        RequestUtils.getToken(getContext(), new MyObserver<BaseBean>(getContext(), false) {
            @Override
            public void onSuccess(BaseBean result) {

            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                if (code == ConfigureFile.code) {
                    OpenFuCard(uuid, carNumber, errorMsg);
                } else {
                    ToastUtils.showToast(context, errorMsg);
                }
            }
        });
    }

    /**
     * 开通副卡接口
     */

    private void OpenFuCard(String uuid, String carNumber, String tokens) {
        String eduMoney = ConverterHelper.toBigDecimal(newMoney).multiply(ConverterHelper.toBigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP).toString();
        Map<String, String> map = new HashMap<>();
        map.put("cardNo", carNumber);
        map.put("companyId", DataUtil.getInstance().getCompanyId());
        map.put("mainCardId", mainCardId);
        map.put("name", fuCardName);
        map.put("productId", productId);
        map.put("payLimit", eduMoney);
        map.put("phone", onePhone);
        map.put("source", "3");
        map.put("staffId", "");
        map.put("storeId", DataUtil.getInstance().getStoreId());
        map.put("subCardType", id);
        map.put("uuid", uuid);
        RequestUtils.CreateSubCard(getContext(), map, tokens, new MyObserver<BaseBean>(getContext()) {
            @Override
            public void onSuccess(BaseBean result) {
                ToastUtils.showToast(getContext(), "操作成功");
                getActivity().finish();
            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                ToastUtils.showToast(getContext(), errorMsg);
                goBack(getActivity());
            }
        });


    }
}
